package com.airS.task.fileMgr.utils.ip;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by alan on 2017/03/17.
 */
public class LatnUtil {

	/**
	 * 获取IP地址,经过F5负载均衡、代理IP等服务器后的真实IP
	 * @param request
	 * @return
     */
	public static String getIpAddr(HttpServletRequest request) {
		if (request == null) {
			return "unknown";
		}
		String ip = request.getHeader("X-Forwarded-For");
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("x-forwarded-for");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取F5转换前的源端口
	 * @param request
	 * @return
     */
	public static String getPort(HttpServletRequest request) {
		String port = "unknown";
		if (null == request) {
			port = "unknown";
		}
		port = request.getHeader("client-source-port");
		if (port == null || port.length() == 0 || "unknown".equalsIgnoreCase(port)) {
			port = request.getHeader("CLIENT-SOURCE-PORT");
		}
		if (port == null || port.length() == 0 || "unknown".equalsIgnoreCase(port)) {
			port = request.getHeader("Client-source-port");
		}
		if (port == null || port.length() == 0 || "unknown".equalsIgnoreCase(port)) {
			port = Integer.toString(request.getRemotePort());
		}

		return port;
	}

	/**
	 * 获取本地IP
	 * @return
     */
	public static List<String> getLocalIPList() {
		List<String> ipList = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
			NetworkInterface networkInterface;
			Enumeration<InetAddress> inetAddresses;
			InetAddress inetAddress;
			String ip;
			while (networkInterfaces.hasMoreElements()) {
				networkInterface = networkInterfaces.nextElement();
				inetAddresses = networkInterface.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					inetAddress = inetAddresses.nextElement();
					if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
						ip = inetAddress.getHostAddress();
						ipList.add(ip);
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return ipList;
	}

}
